package com.example.rxpermissiondemo;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

/**
 * @author josan_tang
 */

public class PermissionManager {
    private static final String TAG = "PermissionManager";
    private List<String> nextNeedRequestPermissions;
    private List<String> noLongerRemindPermissions;
    /**
     * 必须赋予的权限
     */
    public static String[] MUST_GRANTED_PRIMISSION = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};

    private PermissionManager() {
        nextNeedRequestPermissions = new ArrayList<>();
        noLongerRemindPermissions = new ArrayList<>();
    }

    private static class SingletonHolder {
        private static final PermissionManager INSTANCE = new PermissionManager();
    }

    public static PermissionManager getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 是否有权限
     *
     * @param activity
     * @param permissions
     * @return
     */
    public boolean hasPermisson(Activity activity, String... permissions) {
        int unGrantedNum = 0;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (permissions == null || permissions.length <= 0) {
            return true;
        }
        RxPermissions rxPermissions = new RxPermissions(activity);
        for (String permission : permissions) {
            if (!rxPermissions.isGranted(permission)) {
                unGrantedNum++;
            } else {
                if (noLongerRemindPermissions.contains(permission)) {
                    noLongerRemindPermissions.remove(permission);
                }
                if (nextNeedRequestPermissions.contains(permission)) {
                    nextNeedRequestPermissions.remove(permission);
                }
            }
        }
        return unGrantedNum <= 0;
    }

    /**
     * 判断需要授予权限的列表
     *
     * @param activity
     * @param permissons
     * @return
     */
    public List<String> needGrantPermissionList(Activity activity, String... permissons) {
        List<String> needGrantList = new ArrayList<>();
        RxPermissions rxPermissions = new RxPermissions(activity);
        for (String permission : permissons) {
            if (!rxPermissions.isGranted(permission)) {
                needGrantList.add(permission);
            }
        }
        return needGrantList;
    }


    /**
     * 申请非必须的权限
     *
     * @param activity
     * @param callBackListener
     * @param permission
     */
    public void requestPermissionWithNonessential(final Activity activity, final CallBackListener callBackListener, final String permission) {
        if (permission == null) {
            return;
        }
        RxPermissions rxPermissions = new RxPermissions(activity);
        if (rxPermissions.isGranted(permission)) {
            if (callBackListener != null) {
                callBackListener.granted();
            }
            return;
        }
        rxPermissions.requestEach(permission)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (callBackListener != null) {
                            if (permission.granted) {
                                callBackListener.granted();
                            } else {
                                if (permission.shouldShowRequestPermissionRationale) {
                                    callBackListener.refused();
                                } else {
                                    callBackListener.noLongerRemind();
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 必须要被授予的权限
     *
     * @param activity
     * @param permissions
     */
    public void requestPermissionWithEssential(final Activity activity, CallBackListener callBackListener, String... permissions) {
        if (permissions == null || permissions.length == 0) {
            return;
        }
        if (hasPermisson(activity, permissions)) {
            callBackListener.granted();
            return;
        }
        if (noLongerRemindPermissions.size() > 0) {
            if (callBackListener != null) {
                callBackListener.noLongerRemind(noLongerRemindPermissions.toArray(new String[noLongerRemindPermissions.size()]));
                return;
            }
        }
        RxPermissions rxPermissions = new RxPermissions(activity);
        requestPermission(activity, rxPermissions, callBackListener, permissions);
    }

    private void requestPermission(final Activity activity, final RxPermissions rxPermissions, final CallBackListener callBackListener, final String... permissions) {
        rxPermissions.requestEach(permissions)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            Log.d(TAG, "accept: 授予了");
                            if (nextNeedRequestPermissions.contains(permission.name)) {
                                nextNeedRequestPermissions.remove(permission.name);
                            }
                            if (noLongerRemindPermissions.contains(permission.name)) {
                                noLongerRemindPermissions.add(permission.name);
                            }
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            Log.d(TAG, "accept: 拒绝了");
                            if (!nextNeedRequestPermissions.contains(permission.name)) {
                                nextNeedRequestPermissions.add(permission.name);
                            }
                        } else {
                            Log.d(TAG, "accept: 拒绝了，且勾选了不再提醒");
                            if (!noLongerRemindPermissions.contains(permission.name)) {
                                noLongerRemindPermissions.add(permission.name);
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        // noLongerRemindPermissions的判断一定要放在nextNeedRequestPermissions之前
                        // 因为有多个权限时，用户有可能既选了"拒绝，没勾选不再提醒"，又选了"拒绝，且不再提醒"
                        // 当这两种情况都存在时，直接跳转设置页面，让用户赋予权限
                        if (noLongerRemindPermissions.size() > 0) {
                            if (callBackListener != null) {
                                callBackListener.noLongerRemind(noLongerRemindPermissions.toArray(new String[noLongerRemindPermissions.size()]));
                            }
                        } else if (nextNeedRequestPermissions.size() > 0) {
                            showPermissionExplanationDialog(activity, callBackListener);
                        } else {
                            if (callBackListener != null) {
                                callBackListener.granted();
                            }
                        }
                    }
                });
    }

    private void showPermissionExplanationDialog(final Activity activity, final CallBackListener callBackListener) {
//        WccPermissionExplanationDialog dialog = new WccPermissionExplanationDialog(activity, nextNeedRequestPermissions.get(0), new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                requestPermissionWithEssential(activity, callBackListener, nextNeedRequestPermissions.get(0));
//            }
//        });
//        dialog.show();
    }

    /**
     * 申请权限后的回调接口
     */
    public interface CallBackListener {
        void granted();

        void refused();

        void noLongerRemind(String... permissionNames);
    }

    /**
     * 处理回到当前App时，WccActivity对权限对判断
     *
     * @param activity
     * @param childActivity
     */
    public void handleWccActivityPermission(final Activity activity, final Activity childActivity) {
//        // 如果不需要申请权限（一般指已经处于申请权限当流程了），则直接返回
//        if (childActivity != null && childActivity instanceof StartupActivity) {
//            if (!((StartupActivity)childActivity).needApplyPermission) {
//                return;
//            }
//        }
//
//        // 处理必须要有的权限
//        requestPermissionWithEssential(activity, new PermissionManager.CallBackListener() {
//            @Override
//            public void granted() {
//                //重新进行定位请求，避免用户长时间不用，位置信息延迟
//                ((WccApplication) activity.getApplication()).globalInit(activity);
//                HardWare.getInstance(activity).startLocationRunnable(activity);
//                if (childActivity != null) {
//                    if (childActivity instanceof StartupActivity) {
//                        ((StartupActivity) childActivity).loadFlashOrStartNext();
//                    } else if (childActivity instanceof BarcodeScanActivity) {
//                        handleBarcodeScanBack(activity, childActivity);
//                    }
//
//                }
//            }
//
//            @Override
//            public void refused() {
//
//            }
//
//            @Override
//            public void noLongerRemind(String... permissionNames) {
//                showGoSettingDialog(activity, permissionNames[0], false);
//            }
//        }, PermissionManager.MUST_GRANTED_PRIMISSION);
    }

    /**
     * 处理从扫码页面跳转设置去赋予权限后，回到当前页面对逻辑
     *
     * @param activity
     * @param childActivity
     */
    private void handleBarcodeScanBack(final Activity activity, final Activity childActivity) {
//        requestPermissionWithNonessential(activity, new PermissionManager.CallBackListener() {
//            @Override
//            public void granted() {
//                ((BarcodeScanActivity) childActivity).select();
//            }
//
//            @Override
//            public void refused() {
//
//            }
//
//            @Override
//            public void noLongerRemind(String... permissionNames) {
//                showGoSettingDialog(activity, Manifest.permission.CAMERA, true);
//            }
//        }, Manifest.permission.CAMERA);
    }

    /**
     * 显示去设置页面的弹框
     *
     * @param activity
     */
    public void showGoSettingDialog(final Activity activity, String permission, boolean closeActivity) {
//        WccGoSettingDialog dialog = new WccGoSettingDialog(activity, permission, closeActivity, new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (activity instanceof StartupActivity) {
//                    ((StartupActivity)activity).needApplyPermission = true;
//                }
//                goAppDetailSetting(activity);
//            }
//        });
//        dialog.show();
    }

    private void goAppDetailSetting(Context context) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        if (context.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            try {
                context.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    public void goCamera(final Object context, final String filePath, final int requestCode) {
//        Activity activity = null;
//        if (context instanceof Activity) {
//            activity = (Activity) context;
//        } else if (context instanceof Fragment) {
//            activity = ((Fragment) context).getActivity();
//        }
//        if (activity == null) {
//            return;
//        }
//        if (!PermissionManager.getInstance().hasPermisson(activity, Manifest.permission.CAMERA)) {
//            final Activity finalActivity = activity;
//            PermissionManager.getInstance().requestPermissionWithNonessential(finalActivity, new PermissionManager.CallBackListener() {
//                @Override
//                public void granted() {
//                    try {
//                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                        Uri photoUri = FileProviderUtil.getUriForFile(new File(filePath));
//                        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
//                        if (context instanceof Activity) {
//                            ((Activity)context).startActivityForResult(intent, requestCode);
//                        } else if (context instanceof Fragment){
//                            ((Fragment)context).startActivityForResult(intent, requestCode);
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//
//                @Override
//                public void refused() {
//                    Toast.makeText(finalActivity, "拍照需要相机权限", Toast.LENGTH_LONG).show();
//                }
//
//                @Override
//                public void noLongerRemind(String... permissionNames) {
//                    PermissionManager.getInstance().showGoSettingDialog(finalActivity, Manifest.permission.CAMERA, true);
//                }
//            }, Manifest.permission.CAMERA);
//        } else {
//            try {
//                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                Uri photoUri = FileProviderUtil.getUriForFile(new File(filePath));
//                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
//                if (context instanceof Activity) {
//                    ((Activity)context).startActivityForResult(intent, requestCode);
//                } else if (context instanceof Fragment){
//                    ((Fragment)context).startActivityForResult(intent, requestCode);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
    }


}
